﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
    public static partial class contest
    {
        public static dynamic getContestProblemList(int cid, bool god, string player)
        {
            var sql = new Sql.SqlDataContext();
            var con = sql.Contest.Where(row => row.cid == cid).FirstOrDefault();
            if (con == null)
                return new
                {
                    success = false,
                    msg = "比赛不存在"
                };
            bool acright = sql.ContestPlayer.Any(row => row.cid == cid && row.username == player);
            if(!con.is_public && !god && !acright){
                return new
                {
                    success = false,
                    msg = "您没有比赛权限，请与比赛管理员联系"
                };
            }
            int count = sql.ContestProblem.Count(row => (!row.disabled || god) && row.cid == cid);

            var result = (from p in sql.ContestProblem
                          where p.cid == cid
                          orderby p.ps
                          join so in sql.ContestSolve
                           on new { u = player, p.ps } equals new { u = so.username.ToLower(), so.ps }
                           into sos
                          let so = sos.FirstOrDefault()
                          join cps in sql.ContestProblemStatistics
                          on new {p.ps } equals new {cps.ps }
                          into cpso
                          let ps = cpso.FirstOrDefault()
                          select new
                          {
                              ps = p.ps,
                              pid = p.pid,
                              title = p.name,
                              submit = ps.submit,
                              ac = ps.accept,
                              status = so == null ? 0 : so.ac > 0 ? 2 : so.submit > 0 ? 1 : 0
                          });
            return new
            {
                result,
                count,
                success = true
            };
        }
    }
}
